package org.duang.core;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.duang.config.Config;
import org.duang.config.InstanceFactory;
import org.duang.handles.Handles;
import org.duang.render.JsonRender;

@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int contextPathLength;
	private static final String SERVLET_FLAG = "servlet";

	@Override
	public void init(ServletConfig config) throws ServletException {
		InstanceFactory.ServletContext(config.getServletContext());
		String contextPath = config.getServletContext().getContextPath();
		contextPathLength = (null == contextPath || "/".equals(contextPath) ? 0 : contextPath.length());
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Config.getEncoding());
		response.setCharacterEncoding(Config.getEncoding());
		String target = request.getRequestURI();
		if (!target.endsWith(SERVLET_FLAG)) {
			if (contextPathLength > 0) {
				target = target.substring(contextPathLength);// 将请求里的上下文路径去掉
			} 
			try {
				Handles.execute(target, request, response);
				// InstanceFactory.getServletContext().getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(request, response);
				// response.sendRedirect("/WEB-INF/pages/index.jsp");
			} catch (Exception e) {
				e.printStackTrace();
				new JsonRender(e.getMessage()).setContext(request, response).render();
			}
		}
	}
}
